<template>
  <section class="todoapp">
    <HmHeader @AddList="AddList"></HmHeader>
    <HmBody
      :list="renderList"
      @listFlag="listFlag"
      @delList="delList"
      @AllChangeBtn="AllChangeBtn"
      @editList="editList"
      @changeData="changeData"
    ></HmBody>
    <HmFooter
      :AddSum="AddSum"
      :AllListFlag="AllListFlag"
      @RemoveAllCompleted="RemoveAllCompleted"
      :screenList="screenList"
      @screen="screen"
    ></HmFooter>
  </section>
</template>

<script>
import HmHeader from './components/HmHeafer.vue'
import HmBody from './components/HmBody.vue'
import HmFooter from './components/HmFooter.vue'

export default {
  components: {
    HmHeader,
    HmBody,
    HmFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('ExemList')) || [],
      // 定义筛选控制变量
      screenList: 'all',
    }
  },

  methods: {
    // 改变状态事件
    listFlag(id) {
      this.list.forEach((item) => item.id === id && item.flag === !item.flag)
    },
    // 删除事件
    delList(id) {
      this.list = this.list.filter((item) => !(item.id === id))
    },
    // 添加事件
    AddList(value) {
      this.list = [
        ...this.list,
        {
          uname: value,
          id: +new Date(),
          flag: false,
          isShow: true,
        },
      ]
    },
    // 清除所有完成的事件
    RemoveAllCompleted() {
      this.list = this.list.filter((item) => !item.flag)
    },
    AllChangeBtn() {
      // 当list中有一个未完成的就走全部完成等于true，当全部为完成时取反，实现全选和反选
      this.list.every((item) => item.flag)
        ? this.list.forEach((item) => (item.flag = !item.flag))
        : this.list.forEach((item) => (item.flag = true))
    },
    // 筛选按钮传值
    screen(flag) {
      this.screenList = flag
    },
    editList(id) {
      this.list.forEach((item) => item.id === id && (item.isShow = false))
    },
    changeData(id, value) {
      this.list.forEach((item) => {
        if (item.id === id) {
          item.uname = value
          item.isShow = true
        }
      })
    },
  },

  computed: {
    sum: {
      set(value) {
        console.log(value)
      },
      get() {
        return this.list
      },
    },

    // 统计剩余的未完成数量
    AddSum() {
      return this.list.filter((item) => !item.flag).length
    },
    // 控制清除所有已完成按钮（计算出是否有已完成的）
    AllListFlag() {
      return this.list.some((item) => item.flag) //一对全对
    },
    // 根据screenList的值来筛选需要渲染的数据
    renderList() {
      switch (this.screenList) {
        case 'all':
          return this.list
        case 'active':
          return this.list.filter((item) => !item.flag)
        case 'completed':
          return this.list.filter((item) => item.flag)
        default:
          return this.list
      }
    },
  },
  watch: {
    list: {
      deep: true,
      immediate: true,
      handler(newVal) {
        localStorage.setItem('ExemList', JSON.stringify(newVal))
      },
    },
  },
}
</script>

<style></style>
